#include "CollisionManager.h"
#include "ICollidable.h"
#include "Collectable.h"

//gestor de colisoes

namespace PeanutQuest {

	class ICollidable;

	CollisionManager::CollisionManager() : cg::Entity("CollisionManager"){
	}
	CollisionManager::~CollisionManager() {
	}
	
	void CollisionManager::init() {

		shootEnemy = false;

		peanut = (MyPeanut*)cg::Registry::instance()->get("Peanut");
		_sm = (ShooterManager*)cg::Registry::instance()->get("ShooterManager");
		gameManager = (GameManager*)cg::Registry::instance()->get("GameManager");
	}

	void CollisionManager::update(unsigned long elapsed_millis) {

		std::vector<ICollidable*> icollidable_temp = icollidable_vector;

		while(!icollidable_temp.empty()) {
			ICollidable* itemp = icollidable_temp.back();
			icollidable_temp.pop_back();
			for(std::vector<ICollidable*>::iterator it = icollidable_temp.begin(); it != icollidable_temp.end(); ++it) {
				if(testCollision(itemp, *it)) {
					treatCollision(itemp, *it);
					icollidable_temp.erase(std::remove(icollidable_temp.begin(), icollidable_temp.end(), *it), icollidable_temp.end());
					break;
				}
			}
		}
	}
	
	void CollisionManager::add(ICollidable* collidable) {
		icollidable_vector.push_back(collidable);
	}

	bool CollisionManager::testCollision(ICollidable* collidable1, ICollidable* collidable2) {
		resultVector = collidable1->getMyPosition() - collidable2->getMyPosition();
		normalizedVector = length(resultVector);
		normalizedValue = normalizedVector[0];
		radius1 = collidable1->getRadius();
		radius2 = collidable2->getRadius();
		if((normalizedValue < radius1 + radius2) && 
			!(collidable1->getMyPosition()==(0,0,0)) && !(collidable2->getMyPosition()==(0,0,0))) {
				shootEnemy = true;
				return true;
		}
		else { shootEnemy = false; return false; }
	}

	void CollisionManager::treatCollision(ICollidable* collidable1, ICollidable* collidable2) {
		// if the object is collectable by the peanut
		if(collidable1->getStatus() == "collectable") { 
			if(collidable1->getName() == "Rock") {
				_sm->rockCounter++;
				_sm->setMessage("");
			} 
			else if(collidable1->getName() == "Wood") {
				_sm->woodCounter++;
				_sm->setMessage("");
			} 
			else if(collidable1->getName() == "Sugar") { 
				if(gameManager->getLevel() == 1) 
					peanut->setWinMessage("Yey!! You found the sugar :) Congratulations!");
				if(gameManager->getLevel() == 2) 
					peanut->setWinMessage("Yey!! You found the sugar :) Keep going!");
			}
			else if(collidable1->getName() == "Oil") { 
				peanut->setWinMessage("Yey!! You found the oil bottle :) Congratulations! ");
			}
			delete((Collectable*)collidable1);
		} // end of collectable type 

		// if the object is an enemy
		else if(collidable1->getStatus() == "enemy") { 
			peanut->decPeanutLife();
			if(_sm->wasShot && shootEnemy == true) {
				delete((Collectable*)collidable1);
			}
		} // end of enemy type
	}

}